package br.com.ebc.icontatos.jdbcconnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

public abstract class DAOBase {

	/**
	 * @param sql
	 * @return
	 * metodo que executa o sql 
	 * conecta no banco
	 * cria o statement
	 * executa o sql e fecha o statement e a conexao
	 */
	public int executeSQL(String sql) {
		int r = 0;
		Connection com = null;
		Statement st = null;

		try {
			com = DBConnection.getConnection();
			st = com.createStatement();
			r = st.executeUpdate(sql);
		} catch (SQLException e) {
			System.out.println(" Erro! " + e);
		} finally {
			DBConnection.closeStatement(st);
			DBConnection.closeConnection(com);
		}
		return r;
	}
	
	/**
	 * @param condicao
	 * @return
	 * metodo que faz um select no banco recebendo o nome da tabela e a condicao
	 */
	protected Collection selectObjets(String condicao) {
		String sql = " SELECT * FROM " + getTableName() + " " + condicao;
		Connection com = null;
		ResultSet rs = null;
		Statement st = null;
		
		ArrayList objects = new ArrayList();
		
		try{
			com = DBConnection.getConnection();
			st = com.createStatement();
			rs = st.executeQuery(sql);
			
			while(rs.next()){
				objects.add(createObject(rs));
			}
		}catch(SQLException e){
			System.out.println(" Erro " + e);
		}finally{
			DBConnection.closeResultSet(rs);
			DBConnection.closeStatement(st);
			DBConnection.closeConnection(com);
		}
		return objects;
	}
	
	public abstract Object createObject(ResultSet rs)throws SQLException;
	
	public abstract String getTableName();
	
	public Collection selecionarTodos() {
		String condicao = "";
		return selectObjets(condicao);
	}
	
}
